<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="uname" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="uage" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="usex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table
        v-show="this.arr.length !== 0"
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(item.id)">删除</button>
            <button @click="editFn(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  //本地存储
  watch: {
    arr: {
      deep: true,
      handler() {
        localStorage.setItem("arr", JSON.stringify(this.arr));
      },
    },
  },
  methods: {
    addFn() {
      if (this.uname.length === 0 || this.uage <= 0 || this.usex === "")
        return alert("请输入正确的信息");
      if (this.flag === "") {
        this.arr.push({
          id: +new Date(),
          name: this.uname,
          age: this.uage,
          sex: this.usex,
        });
      } else {
        this.flag.name = this.uname;
        this.flag.age = this.uage;
        this.flag.sex = this.usex;
        this.flag = "";
      }
      this.uname = "";
      this.uage = "";
      this.usex = "";
    },
    delFn(id) {
      console.log(id);
      this.arr = this.arr.filter((item) => item.id != id);
    },
    editFn(id) {
      let obj = this.arr.find((item) => item.id === id);
      console.log(obj);
      //数据回显
      const { name, age, sex } = obj;
      this.uname = name;
      this.uage = age;
      this.usex = sex;

      this.flag = obj;
    },
  },
  data() {
    return {
      uname: "",
      uage: "",
      usex: "",
      flag: "",
      arr: JSON.parse(localStorage.getItem("arr")) || [],
    };
  },
};
</script>
